package com.gzhryc.shared_device.oem.h5.mng;

import com.gzhryc.shared_device.common.BusyThreadPool;
import com.gzhryc.shared_device.oem.code.member.services.MemberService;
import com.gzhryc.shared_device.oem.code.member.services.dto.MemberSearch;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 用于会员分表处理
 */
public class MemberTableHelper {

    private static List<TableItem> tableItemList = new ArrayList<>();;
    private static AtomicBoolean isRefresh = new AtomicBoolean(false);

    static {
        tableItemList.clear();
        for (long i = 1; i <= 9; i++) {
            TableItem item = new TableItem();
            item.setId(i);
            item.setName("分表" + i);
            tableItemList.add(item);
        }
    }

    public static List<TableItem> getTableItem(){
        List<TableItem> result = new ArrayList<>(tableItemList);
        return result;
    }

    public static void refresh(){
        if(isRefresh.compareAndSet(false,true)) {
            BusyThreadPool.self().execute(new RefreshData());
        }
    }

    private static class RefreshData implements Runnable{

        @Override
        public void run() {
            List<TableItem> idPrefixList = new ArrayList<>();
            for (long i = 1; i <= 9; i++) {
                MemberSearch search = new MemberSearch();
                search.setIdPrefix(i);
                Long total = MemberService.self().countBySearch(search);

                TableItem item = new TableItem();
                item.setId(i);
                item.setName("分表" + i + "(数据量：" + total + ")");
                idPrefixList.add(item);
            }
            tableItemList = idPrefixList;
            isRefresh.set(false);
        }
    }


    public static class TableItem {

        private Long id;
        private String name;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
